<template>
  <div class="page">
    <div class="chatBox">
      <!-- API Key设置对话框 -->
      <div class="dialog key-dialog" v-show="setKeyDialog">
        <div class="dialog-header">设置API Key</div>
        <div class="dialog-body">
          <input type="text" v-model="key" placeholder="请输入您的API Key" @keyup.enter="doSetKey"/>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-cancel" @click="setKeyDialog = false">取消</button>
          <button class="btn btn-confirm" @click="doSetKey()">确认</button>
        </div>
      </div>
      
      <!-- 文件上传对话框 -->
      <div class="dialog file-dialog" v-show="uploadDialog">
        <div class="dialog-header">上传文档</div>
        <div class="dialog-body">
          <div class="file-upload">
            <label for="file-input" class="file-label">
              <span v-if="!selectedFile">选择PDF文件</span>
              <span v-else>{{ selectedFile.name }}</span>
            </label>
            <input type="file" id="file-input" ref="file" accept=".pdf" @change="handleFileChange" />
          </div>
          <div class="file-info" v-if="selectedFile">
            <p>文件大小: {{ formatFileSize(selectedFile.size) }}</p>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="btn btn-cancel" @click="cancelUpload">取消</button>
          <button class="btn btn-confirm" @click="doUpload()" :disabled="!selectedFile">上传</button>
        </div>
      </div>
      
      <!-- 遮罩层 -->
      <div class="overlay" v-if="setKeyDialog || uploadDialog" @click="closeAllDialogs"></div>
      
      <!-- 侧边栏 -->
      <div class="sidebar">
        <div class="head">
          <img src="./assets/2.webp" alt="头像" />
        </div>
        <ul class="sidebar-menu">
          <li class="sidebar-item" @click="showSetKeyDialog()" title="设置API Key">
            <i class="iconfont icon-icon_shezhi"></i>
          </li>
          <li class="sidebar-item" @click="showUploadDialog()" title="上传文档">
            <i class="iconfont icon-wenjian"></i>
          </li>
        </ul>
      </div>
      
      <!-- 主聊天区域 -->
      <div class="chat-container">
        <div class="chat-header">
          <h2>智能文档助手</h2>
        </div>
        
        <div class="chat-messages" ref="messageContainer">
          <div v-for="(item, index) in information" :key="index" 
               :class="['message', getMessageClass(item, index)]">
            <div class="message-content" v-html="item"></div>
          </div>
          <div class="typing-indicator" v-if="isLoading">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
        
        <div class="chat-input">
          <textarea 
            placeholder="请输入您的问题..." 
            v-model="sub" 
            :disabled="isDisabled"
            @keyup.enter.exact="submitt"
            ref="inputArea"
          ></textarea>
          <button 
            class="send-button" 
            @click="submitt()" 
            :disabled="isDisabled || !sub.trim()"
            :class="{'send-button-disabled': isDisabled || !sub.trim()}"
          >
            <i class="iconfont icon-fasong"></i>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 提示消息 -->
    <div class="toast" v-show="toast.show">{{ toast.message }}</div>
  </div>
</template>

<script>
import api from '@/api/chatApi'
import axios from 'axios'

export default {
  name: 'App',
  data() {
    return {
      setKeyDialog: false,
      uploadDialog: false,
      key: '',
      sub: '',
      isDisabled: false,
      isLoading: false,
      selectedFile: null,
      information: ['请先设置API Key，并且上传您的PDF文档，我的回答将会基于该文档。'],
      toast: {
        show: false,
        message: '',
        timer: null
      }
    }
  },
  mounted() {
    // 检查是否已经设置了API Key
    this.checkApiKey();
    
    // 添加窗口大小调整事件监听器
    window.addEventListener('resize', this.adjustTextareaSize);
    this.adjustTextareaSize();
  },
  beforeDestroy() {
    // 移除事件监听器
    window.removeEventListener('resize', this.adjustTextareaSize);
    
    // 清除任何可能存在的定时器
    if (this.toast.timer) {
      clearTimeout(this.toast.timer);
    }
  },
  watch: {
    // 监听消息列表变化，自动滚动到底部
    information: {
      deep: true,
      handler() {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    }
  },
  methods: {
    // 获取消息类名
    getMessageClass(message, index) {
      if (typeof message === 'string' && message.startsWith('ERROR:')) {
        return 'message-error';
      }
      return index % 2 ? 'message-user' : 'message-assistant';
    },
    
    // 检查API Key是否已设置
    checkApiKey() {
      // 这里可以添加检查API Key是否已设置的逻辑
      // 如果需要从本地存储或其他地方获取
    },
    
    // 显示设置API Key对话框
    showSetKeyDialog() {
      this.setKeyDialog = true;
      this.uploadDialog = false;
    },
    
    // 显示上传文件对话框
    showUploadDialog() {
      this.uploadDialog = true;
      this.setKeyDialog = false;
    },
    
    // 关闭所有对话框
    closeAllDialogs() {
      this.setKeyDialog = false;
      this.uploadDialog = false;
    },
    
    // 设置API Key
    doSetKey() {
      if (!this.key.trim()) {
        this.showToast('请输入有效的API Key');
        return;
      }
      
      this.isLoading = true;
      api.saveKey('Bearer ' + this.key)
        .then(resp => {
          this.showToast('API Key设置成功');
          this.setKeyDialog = false;
        })
        .catch(error => {
          this.showToast('API Key设置失败: ' + (error.message || '未知错误'));
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    
    // 处理文件选择变化
    handleFileChange(event) {
      const files = event.target.files;
      if (files.length > 0) {
        const file = files[0];
        
        // 检查文件类型
        if (file.type !== 'application/pdf') {
          this.showToast('请选择PDF文件');
          this.$refs.file.value = '';
          this.selectedFile = null;
          return;
        }
        
        // 检查文件大小 (限制为10MB)
        if (file.size > 10 * 1024 * 1024) {
          this.showToast('文件大小不能超过10MB');
          this.$refs.file.value = '';
          this.selectedFile = null;
          return;
        }
        
        this.selectedFile = file;
      } else {
        this.selectedFile = null;
      }
    },
    
    // 取消上传
    cancelUpload() {
      this.$refs.file.value = '';
      this.selectedFile = null;
      this.uploadDialog = false;
    },
    
    // 上传文件
    doUpload() {
      if (!this.selectedFile) {
        this.showToast('请选择要上传的文件');
        return;
      }
      
      this.isLoading = true;
      
      // 创建FormData对象
      const formData = new FormData();
      formData.append('file', this.selectedFile);
      
      axios.post(
        '/api/api/upload',
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
      ).then(resp => {
        this.showToast('文件上传成功');
        this.uploadDialog = false;
        this.selectedFile = null;
        this.$refs.file.value = '';
      }).catch(error => {
        this.showToast('文件上传失败: ' + (error.message || '未知错误'));
      }).finally(() => {
        this.isLoading = false;
      });
    },
    
    // 发送消息
    submitt() {
      const message = this.sub.trim();
      if (!message) return;
      
      // 添加用户消息到聊天
      this.information.push(message);
      this.isDisabled = true;
      this.isLoading = true;
      
      // 清空输入框
      this.sub = '';
      
      // 发送API请求
      api.chat(message)
        .then(resp => {
          if (resp && resp.data) {
            // 添加助手回复到聊天
            this.information.push(resp.data);
          } else {
            this.showToast('获取回复失败');
          }
        })
        .catch(error => {
          // 将错误消息添加到聊天列表中
          this.information.push(`ERROR: ${error.message || '未知错误'}`);
        })
        .finally(() => {
          this.isDisabled = false;
          this.isLoading = false;
          this.$nextTick(() => {
            this.$refs.inputArea.focus();
          });
        });
    },
    
    // 显示提示消息
    showToast(message, duration = 3000) {
      // 清除之前的定时器
      if (this.toast.timer) {
        clearTimeout(this.toast.timer);
      }
      
      // 显示新的提示消息
      this.toast.message = message;
      this.toast.show = true;
      
      // 设置定时器自动隐藏
      this.toast.timer = setTimeout(() => {
        this.toast.show = false;
      }, duration);
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes < 1024) return bytes + ' B';
      else if (bytes < 1048576) return (bytes / 1024).toFixed(2) + ' KB';
      else return (bytes / 1048576).toFixed(2) + ' MB';
    },
    
    // 滚动到消息容器底部
    scrollToBottom() {
      if (this.$refs.messageContainer) {
        this.$refs.messageContainer.scrollTop = this.$refs.messageContainer.scrollHeight;
      }
    },
    
    // 调整文本区域大小
    adjustTextareaSize() {
      if (this.$refs.inputArea) {
        // 不再手动设置宽度，让CSS的flex布局自动处理
        // textarea已设置为flex: 1，会自动填充可用空间
        this.$refs.inputArea.style.width = '';
      }
    }
  }
}
</script>

<style lang="less" scoped>
// 全局动画定义
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translate(-50%, -60%);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
}

@keyframes slideOut {
  from {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
  to {
    opacity: 0;
    transform: translate(-50%, -60%);
  }
}

@keyframes scaleIn {
  from {
    transform: scale(0.95);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}

.page {
  margin: 0;
  padding: 0;
  min-height: 100vh;
  background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d);
  background-size: 400% 400%;
  animation: gradientBG 15s ease infinite;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chatBox {
  position: relative;
  width: 95%;
  max-width: 1400px;
  height: 80vh;
  max-height: 900px;
  background-color: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(15px);
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  display: flex;
  overflow: hidden;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-sizing: border-box;
}

@keyframes gradientBG {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

// 对话框样式
.dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 90%;
  max-width: 450px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
  z-index: 1000;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  overflow: hidden;
  animation: slideIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  
  .dialog-header {
    padding: 20px;
    font-size: 20px;
    font-weight: 600;
    color: #333;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    background: linear-gradient(to right, rgba(110, 72, 170, 0.1), rgba(157, 80, 187, 0.1));
  }
  
  .dialog-body {
    padding: 25px;
    
    input[type="text"] {
      width: 100%;
      padding: 15px;
      border: 2px solid #ddd;
      border-radius: 12px;
      font-size: 15px;
      transition: all 0.3s ease;
      
      &:focus {
        border-color: #6e48aa;
        outline: none;
        box-shadow: 0 0 10px rgba(110, 72, 170, 0.2);
      }
    }
    
    .file-upload {
      border: 2px dashed rgba(110, 72, 170, 0.3);
      border-radius: 16px;
      padding: 30px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      background: rgba(110, 72, 170, 0.05);
      position: relative;
      overflow: hidden;
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: radial-gradient(circle at center, rgba(110, 72, 170, 0.2) 0%, transparent 70%);
        opacity: 0;
        transition: opacity 0.3s ease;
      }
      
      &:hover {
        border-color: #6e48aa;
        background: rgba(110, 72, 170, 0.1);
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(110, 72, 170, 0.1);
        
        &::before {
          opacity: 1;
          animation: pulse 2s infinite;
        }
      }
      
      &.drag-over {
        border-color: #6e48aa;
        background: rgba(110, 72, 170, 0.15);
        transform: scale(1.02);
        box-shadow: 0 6px 20px rgba(110, 72, 170, 0.2);
      }
      
      input[type="file"] {
        display: none;
      }
      
      .file-label {
        color: rgba(255, 255, 255, 0.8);
        font-size: 16px;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 10px;
      }
    }
    
    .file-info {
      margin-top: 15px;
      font-size: 14px;
      color: rgba(110, 72, 170, 0.8);
      padding: 12px;
      background: rgba(110, 72, 170, 0.05);
      border-radius: 12px;
      border: 1px solid rgba(110, 72, 170, 0.2);
    }
  }
  
  .dialog-footer {
    padding: 20px;
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    border-top: 1px solid rgba(110, 72, 170, 0.1);
    background: rgba(255, 255, 255, 0.05);
  }
}

// 遮罩层
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(2px);
  z-index: 999;
}

// 侧边栏
.sidebar {
  width: 70px;
  background: rgba(255, 255, 255, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
  border-right: 1px solid rgba(255, 255, 255, 0.1);
  
  .head {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    overflow: hidden;
    margin-bottom: 25px;
    border: 2px solid rgba(255, 255, 255, 0.5);
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
    transition: transform 0.3s ease;
    
    &:hover {
      transform: scale(1.1);
    }
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  .sidebar-menu {
    list-style: none;
    padding: 0;
    margin: 0;
    width: 100%;
    
    .sidebar-item {
      width: 100%;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      cursor: pointer;
      transition: all 0.3s;
      
      &:hover {
        background: rgba(255, 255, 255, 0.1);
      }
      
      i {
        font-size: 20px;
      }
    }
  }
}

// 主聊天区域
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.05);
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
  
  .chat-header {
    padding: 16px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    
    h2 {
      color: white;
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }
  }
  
  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    scroll-behavior: smooth;
    
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: rgba(255, 255, 255, 0.2);
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-track {
      background: rgba(0, 0, 0, 0.05);
    }
    
    .message {
      margin-bottom: 20px;
      max-width: 80%;
      
      &.message-assistant {
        margin-right: auto;
        
        .message-content {
          background: rgba(255, 255, 255, 0.15);
          color: white;
          border-radius: 18px 18px 18px 4px;
          box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
          border-left: 3px solid #64ffda;
        }
      }
      
      &.message-user {
        margin-left: auto;
        
        .message-content {
          background: linear-gradient(135deg, #6e48aa, #9d50bb);
          color: white;
          border-radius: 18px 18px 4px 18px;
          box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
      }
      
      &.message-error {
        margin-right: auto;
        
        .message-content {
          background: rgba(255, 59, 48, 0.2);
          color: #ff3b30;
          border-radius: 18px 18px 18px 4px;
          box-shadow: 0 2px 10px rgba(255, 59, 48, 0.1);
          border-left: 3px solid #ff3b30;
          font-weight: 500;
        }
      }
      
      .message-content {
        padding: 14px 18px;
        font-size: 15px;
        line-height: 1.6;
        transition: transform 0.2s ease;
        
        &:hover {
          transform: translateY(-2px);
        }
      }
    }
    
    .typing-indicator {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      padding: 12px 16px;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 12px 12px 12px 0;
      
      span {
        width: 6px;
        height: 6px;
        background: white;
        border-radius: 50%;
        animation: typing 1s infinite;
        
        &:nth-child(2) { animation-delay: 0.2s; }
        &:nth-child(3) { animation-delay: 0.4s; }
      }
    }
  }
  
  .chat-input {
    padding: 20px;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    display: flex;
    align-items: flex-end;
    background: rgba(255, 255, 255, 0.05);
    width: 100%;
    box-sizing: border-box;
    
    textarea {
      flex: 1;
      min-height: 24px;
      max-height: 120px;
      padding: 15px 20px;
      border: 2px solid rgba(255, 255, 255, 0.2);
      border-radius: 20px;
      background: rgba(255, 255, 255, 0.1);
      color: white;
      font-size: 15px;
      resize: none;
      transition: all 0.3s ease;
      margin-right: 15px;
      box-sizing: border-box;
      width: calc(100% - 65px); /* 考虑按钮宽度和间距 */
      overflow-y: auto;
      
      &:focus {
        outline: none;
        border-color: #64ffda;
        background: rgba(255, 255, 255, 0.15);
        box-shadow: 0 0 15px rgba(100, 255, 218, 0.2);
      }
      
      &::placeholder {
        color: rgba(255, 255, 255, 0.5);
      }
    }
    
    .send-button {
      width: 50px;
      height: 50px;
      min-width: 50px; /* 确保最小宽度 */
      border: none;
      border-radius: 25px;
      background: linear-gradient(135deg, #6e48aa, #9d50bb);
      color: white;
      cursor: pointer;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0; /* 防止按钮被压缩 */
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
      }
      
      &:active {
        transform: translateY(1px);
      }
      
      &.send-button-disabled {
        background: rgba(255, 255, 255, 0.2);
        cursor: not-allowed;
        box-shadow: none;
        
        &:hover {
          transform: none;
        }
      }
      
      i {
        font-size: 20px;
      }
    }
  }
}

// 提示消息
.toast {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 12px 24px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  border-radius: 6px;
  font-size: 14px;
  z-index: 1001;
  animation: fadeInOut 0.3s ease-in-out;
}

// 按钮样式
.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 12px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &.btn-confirm {
    background: linear-gradient(135deg, #6e48aa, #9d50bb);
    color: white;
    box-shadow: 0 4px 15px rgba(110, 72, 170, 0.3);
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(110, 72, 170, 0.4);
    }
    
    &:active {
      transform: translateY(1px);
    }
    
    &:disabled {
      background: linear-gradient(135deg, #ccc, #999);
      cursor: not-allowed;
      box-shadow: none;
      
      &:hover {
        transform: none;
      }
    }
  }
  
  &.btn-cancel {
    background: rgba(255, 255, 255, 0.1);
    color: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(5px);
    
    &:hover {
      background: rgba(255, 255, 255, 0.15);
      transform: translateY(-2px);
    }
    
    &:active {
      transform: translateY(1px);
    }
  }
}

// 动画
@keyframes typing {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-4px); }
}

@keyframes fadeInOut {
  from { opacity: 0; transform: translate(-50%, -10px); }
  to { opacity: 1; transform: translate(-50%, 0); }
}

// 响应式设计
@media (max-width: 768px) {
  .chatBox {
    width: 100%;
    height: 100vh;
    border-radius: 0;
  }
  
  .dialog {
    width: 95%;
  }
  
  .chat-messages {
    .message {
      max-width: 90%;
    }
  }
}
</style>